<?php

namespace app\api\controller;

use app\admin\model\Goods as GoodsModel;
use app\admin\model\Usercollect as Usercollect;
use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Config;
use think\Env;
use think\Log;
use think\Validate;

/**
 * 收藏接口
 */
class Collect extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];
    public function _initialize(){
        parent::_initialize();

        $this->Goods = new GoodsModel;
        $this->Usercollect = new Usercollect;
    }
    /**
     * 收藏列表
     */
    public function index()
    {
        $user = $this->auth->getUser();
        $goods = $this->Goods;
        $goods = $this->collect($goods,$user);
        $limit = request()->param('limit',20);
        $goods = $goods->order('createtime','desc')->paginate($limit);
        $this->success('请求成功',[
            'collect'=>$goods,
        ]);
    }
    /**
     * 收藏
     * @return void
     */
    public function collect($goods,$user)
    {
        $collect = db('user_collect')->where('user_id',$user->id)->field('id,good_id,user_id')->select();
        $arr = [];
        if(!empty($collect)){
            foreach ($collect as $v){
                array_push($arr,$v['good_id']);
            }
        }
        $goods = $goods->whereIn('id',$arr);
        return $goods;
    }

    /**
     * 添加收藏
     * @return void
     */
    public function add()
    {
        $user = $this->auth->getUser();
        $goods_id = request()->param('goods_id');
        if(!$goods_id){
            $this->error('参数不全');
        }
        $collect = $this->Usercollect->where(['user_id'=>$user->id,'good_id'=>$goods_id])->find();
        if($collect){
            $this->error('已收藏过');
        }
        $this->Usercollect->insert([
            'user_id'=>$user->id,
            'good_id'=>$goods_id
        ]);
        $this->success('收藏成功');
    }

    /**
     * 取消收藏
     * @return void
     */
    public function del()
    {
        $user = $this->auth->getUser();
        $goods_id = request()->param('goods_id');
        if(!$goods_id){
            $this->error('参数错误');
        }
        $collect = $this->Usercollect->where(['user_id'=>$user->id,'good_id'=>$goods_id])->delete();
        if($collect){
            $this->success('取消收藏成功');
        }
        $this->error('取消收藏失败');
    }
}
